package com.sgb.kjwl.view.ui.activity.pick;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.sgb.alimaplibrary.MapLocationTools;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityPickNoticeDetailBinding;
import com.sgb.kjwl.di.pick.DaggerPickComponent;
import com.sgb.kjwl.di.pick.PickModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.pick.PrePickNoticeDetailEntity;
import com.sgb.kjwl.model.entity.pick.TenderDictEntity3;
import com.sgb.kjwl.model.entity.pick.TenderInfoBasicEntity3;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.GetPositionActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickNoticeDetailItemAdapter;
import com.sgb.kjwl.view.ui.adapter.pick.PickNoticeDetailsAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.widget.pick.PickEmploymentShareDialog;
import com.sgb.kjwl.viewmodel.pick.PickNoticeDetailModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.sql.Timestamp;
import java.util.List;

import javax.inject.Inject;

public class PickNoticeDetailActivity extends AppActivity{

    private ActivityPickNoticeDetailBinding binding;
    private int type;

    @Inject
    PickNoticeDetailModel detailModel;

    private PickNoticeDetailItemAdapter adapter;
    private String noticeId;
    private MapLocationTools mapLocationTools;

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, PickNoticeDetailActivity.class);
        intent.putExtra("noticeId", id);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPickComponent.builder()
                .appComponent(appComponent)
                .pickModule(new PickModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pick_notice_detail);
        binding.ivBack.setOnClickListener(view -> finish());
        binding.setClickListener(this);
        binding.setViewModel(detailModel);
        binding.focusState.setOnClickListener(this);
        binding.tvReport.setOnClickListener(this);
        binding.imageReport.setOnClickListener(this);
        binding.tvUserFocus.setOnClickListener(this);
        binding.imageUserFocus.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);
        binding.shareImageView.setOnClickListener(this);

        adapter = new PickNoticeDetailItemAdapter(getActivity(), null);
        binding.pickRecycler.setSectionedRecyclerViewAdapter(adapter);
        binding.pickRecycler.setLoadingMoreEnabled(false);
        binding.pickRecycler.setPullRefreshEnabled(false);
        GridLayoutManager rightManager = new GridLayoutManager(getActivity(), 1);
        binding.pickRecycler.setLayoutManager(rightManager);
        binding.pickRecycler.setAdapter(adapter);

    }

    @Override
    protected void init() {
        noticeId = getIntent().getStringExtra("noticeId");
        detailModel.getDetail(noticeId);
    }

    public void showData(List<TenderInfoBasicEntity3<TenderDictEntity3>> entity) {
        if (entity != null && entity.size() > 0) {
            for (int i = 0; i < entity.size(); i++) {
                List<TenderDictEntity3> tenderDictEntity3List = entity.get(i).getDatas();
                for (int j = 0; j < tenderDictEntity3List.size(); j++) {
                    TenderDictEntity3 tenderDictEntity3 = tenderDictEntity3List.get(j);
                    if (tenderDictEntity3.getName() == "" && tenderDictEntity3.getValue() == "") {
                        entity.get(i).getDatas().remove(j);
                    }
                }
                if(entity.get(i).getGroupName().equals("投标人条件要求")){
                    entity.get(i).setGroupName("投标人资格");
                }
            }
            adapter.setData(entity);
        } else {
            binding.linePickRecycler.setVisibility(View.GONE);
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerPickNoticeMain.setLayoutManager(layoutManager);
        PickNoticeDetailsAdapter pickNoticeDetailsAdapter = new PickNoticeDetailsAdapter(getActivity(), detailModel.detailEntity.get());
        binding.recyclerPickNoticeMain.setAdapter(pickNoticeDetailsAdapter);
        pickNoticeDetailsAdapter.setOnItemClick(new PickNoticeDetailsAdapter.OnItemClick() {
            @Override
            public void onMapClick(String lat, String lag, String address) {
                PickCompanyLocationMapActivity.start(PickNoticeDetailActivity.this, lat, lag, address, detailModel.detailEntity.get().getNoticeInfo().getComName());
            }

            @Override
            public void onDistanceClick(String lat, String lag, String address) {
                Double latt = Double.valueOf(lat);
                Double log = Double.valueOf(lag);
                GetPositionActivity.start(getActivity(), log, latt, address);
            }
        });

        PrePickNoticeDetailEntity.NoticeInfoBean noticeInfoBean = detailModel.detailEntity.get().getNoticeInfo();

        if (noticeInfoBean.getName().length() <= 15) {
            binding.titleView.setText(noticeInfoBean.getName());
        } else {
            binding.titleView.setText(noticeInfoBean.getName().substring(0, 12) + "...");
        }
        if (noticeInfoBean.getShowEndTimeFlag() == 0) {
            binding.tvEndTime.setVisibility(View.GONE);
        } else {
            binding.tvEndTime.setVisibility(View.VISIBLE);
            showCudownTime();
        }
        binding.toCompany.setText(noticeInfoBean.getComName());
        if (noticeInfoBean.isConcernEnterprises()) {
            binding.focusState.setText("已关注");
            binding.focusState.setTextColor(getResources().getColor(R.color.color_input_hint));
            binding.focusState.setBackgroundResource(R.drawable.corner5_999999_bg);
        } else {
            binding.focusState.setText("关注");
            binding.focusState.setTextColor(getResources().getColor(R.color.color_main));
            binding.focusState.setBackgroundResource(R.drawable.corner5_ff2928_bg_pick);
        }
        //标是否关注
        if (noticeInfoBean.getUserFocusFlag() == 0) {
            binding.imageUserFocus.setImageDrawable(getResources().getDrawable(R.mipmap.guanzhu_pick));
            binding.tvUserFocus.setText("关注");
            binding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_tab_two));
        } else {
            binding.imageUserFocus.setImageDrawable(getResources().getDrawable(R.mipmap.yiguanzhu_pick));
            binding.tvUserFocus.setText("已关注");
            binding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_main));
        }
    }

    public void setIsGz(boolean isGz) {
        if (isGz) {
            binding.focusState.setText("关注");
            binding.focusState.setTextColor(getResources().getColor(R.color.color_main));
            binding.focusState.setBackgroundResource(R.drawable.corner5_ff2928_bg_pick);
            detailModel.detailEntity.get().getNoticeInfo().setConcernEnterprises(false);
            MToast.showLongToast1(this, "已取消关注企业", Gravity.CENTER);
        } else {
            binding.focusState.setText("已关注");
            binding.focusState.setTextColor(getResources().getColor(R.color.color_input_hint));
            binding.focusState.setBackgroundResource(R.drawable.corner5_999999_bg);
            detailModel.detailEntity.get().getNoticeInfo().setConcernEnterprises(true);
            MToast.showLongToast1(this, "关注企业成功", Gravity.CENTER);
        }
    }

    public void setTvIsGz(int isGz) {
        //标是否关注
        if (isGz == 1) {
            binding.imageUserFocus.setImageDrawable(getResources().getDrawable(R.mipmap.guanzhu_pick));
            binding.tvUserFocus.setText("关注");
            binding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_tab_two));
            detailModel.detailEntity.get().getNoticeInfo().setUserFocusFlag(0);
            MToast.showLongToast1(this, "已取消关注招标", Gravity.CENTER);
        } else {
            binding.imageUserFocus.setImageDrawable(getResources().getDrawable(R.mipmap.yiguanzhu_pick));
            binding.tvUserFocus.setText("已关注");
            binding.tvUserFocus.setTextColor(getResources().getColor(R.color.color_main));
            detailModel.detailEntity.get().getNoticeInfo().setUserFocusFlag(1);
            MToast.showLongToast1(this, "关注招标成功", Gravity.CENTER);
        }
    }

    private void showCudownTime() {
        if (!TextUtils.isEmpty(detailModel.detailEntity.get().getNoticeInfo().getApplyStartTime())) {
            String st = DateUtils.stampToDate(detailModel.detailEntity.get().getNoticeInfo().getApplyStartTime());//结束或者开始时间
            String nt = DateUtils.stampToDate(System.currentTimeMillis() + "");//当前时间
            Timestamp t = Timestamp.valueOf(st);
            Timestamp n = Timestamp.valueOf(nt);
            if (n.before(t)) {
                //没过期
                long nl = System.currentTimeMillis();
                long sl = (long) Long.valueOf(detailModel.detailEntity.get().getNoticeInfo().getApplyStartTime());
                time2((sl - nl) / 1000, "报名开始倒计时: ");
            }
        }
    }

    private long midTime;
    private String info;

    public void time2(long midTime, String info) {
        this.midTime = midTime;
        this.info = info;
        runnable.run();
    }

    private Runnable runnable = new Runnable() {
        private String time;

        @Override
        public void run() {
            if (midTime > 0) {
                midTime--;
                /*long dd = midTime / 24 / 60 / 60 % 60;
                long hh = (midTime - dd * 24 * 60 * 60) / 60 / 60 % 60;
                long mm = (midTime - dd * 24 * 60 * 60 - hh * 60 * 60) / 60 % 60;
                long ss = midTime % 60;*/
                long dd = midTime / 86400;
                long hh = midTime % 86400 / 3600;            //转换小时
                long mm = midTime % 86400 % 3600 / 60;            //转换分钟
                long ss = midTime % 86400 % 3600 % 60;            //剩余秒数

                if (dd > 0) {
                    time = info + dd + "天" + hh + "小时" + mm + "分钟" + ss + "秒";
                } else {
                    if (hh > 0) {
                        time = info + hh + "小时" + mm + "分钟" + ss + "秒";
                    } else {
                        if (mm > 0) {
                            time = info + mm + "分钟" + ss + "秒";
                        } else {
                            time = info + ss + "秒";
                        }
                    }
                }
                Message message = Message.obtain();
                message.what = 3;
                message.obj = time;
                timeHandler.sendMessage(message);
//                Log.e("倒计时", time);
                timeHandler.postDelayed(runnable, 1000);
            } else {
                timeHandler.removeCallbacks(runnable);
            }
        }
    };

    private Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 3) {
                binding.tvEndTime.setText((String) msg.obj);
            }
        }
    };

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.to_company:
                if (TextUtils.isEmpty(detailModel.detailEntity.get().getNoticeInfo().getComNo())) {
                    ToastUtil.show(getActivity(), "企业店铺no不能为空");
                    return;
                }
                WebsiteInfoActivity.start(getActivity(), detailModel.detailEntity.get().getNoticeInfo().getComNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
                break;
            case R.id.focusState:
                type = 0;
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    checkAddTokenView();
                }
                break;
            case R.id.tv_user_focus:
            case R.id.image_user_focus:
                type = 1;
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    checkAddTokenView();
                }
                break;
            case R.id.tv_report:
            case R.id.image_report:
                ReportActivity.start(this, noticeId, "1");
                break;
            case R.id.img_back_top:
                binding.neSc.fullScroll(View.FOCUS_UP);
                break;
            case R.id.share_image_view:
                if (!ClickUtils.isDoubleClick()) {
                    PickEmploymentShareDialog dialog = new PickEmploymentShareDialog(detailModel.detailEntity.get().getNoticeInfo().getName(),detailModel.detailEntity.get().getNoticeInfo().getWeixinFenXiangUrl(),
                            detailModel.detailEntity.get().getNoticeInfo().getWeixinFenXiangMsg(),
                            detailModel.detailEntity.get().getNoticeInfo().getTenderTypeName(),
                            detailModel.detailEntity.get().getNoticeInfo().getMoney(),
                            detailModel.detailEntity.get().getNoticeInfo().getComName(),2,this,null);
                    dialog.setDialogClickCallBack(new PickEmploymentShareDialog.DialogClickCallBack() {
                        @Override
                        public void onItemClick(String name) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.show(PickNoticeDetailActivity.this,name);
                                }
                            });
                        }
                    }).show();
                }
                break;
        }
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_NOTICE_DETAIL_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void checkTokenView() {
        Intent intent = new Intent();
        intent.putExtra("showPage", "FRAGMENT_SHOPPING");
        MainActivity.start(PickNoticeDetailActivity.this, intent);

    }

    public void toLogin() {
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, "");
        MToast.showToast(this, "登录失效，请重新登录");
        //LoginActivity.start(this);
        jumpLogin();
    }

    public void checkAddTokenView() {
        if (type == 0) {//关注企业
            detailModel.userFocus(detailModel.detailEntity.get().getNoticeInfo().getComNo(), detailModel.detailEntity.get().getNoticeInfo().isConcernEnterprises());
        } else {
            detailModel.editTender(detailModel.detailEntity.get().getNoticeInfo().getTenderNo(), detailModel.detailEntity.get().getNoticeInfo().getUserFocusFlag());
        }
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(PickNoticeDetailActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(PickNoticeDetailActivity.this, EventConstant.EVENT_NOTICE_DETAIL_JUMP);
        }
    }

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(PickNoticeDetailActivity.this, EventConstant.EVENT_NOTICE_DETAIL_JUMP);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    detailModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        String localLng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        String localLat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        if (localLng == "" && localLat == "") {
            getLoction();
        }
    }

    private void getLoction() {
        if (mapLocationTools == null){
            mapLocationTools = new MapLocationTools(getActivity());
        }
        mapLocationTools.initLocation(false);
        mapLocationTools.setLocationListener(new MapLocationTools.LocationListener() {
            @Override
            public void getLocationListener(String address, Double Longitude, Double Latitude) {
                SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE_ID,String.valueOf(Longitude));
                SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE_ID,String.valueOf(Latitude));
            }
        });
        mapLocationTools.startLocation();
    }
}
